/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package nio_client;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

public class NIO_Client 
{
  
    public static void main(String[] args) throws IOException 
    {
          String host = "localhost";
            
	  int port = 2000;                   
                                           
	  SocketAddress sad = new InetSocketAddress(host, port);
            
	  SocketChannel sc = SocketChannel.open();
            
	   sc.connect(sad);
            
	   sc.configureBlocking(true);

	   File file = new File("C:/JavaExample/file11.txt");
                          
           long start = System.currentTimeMillis();
            
           NIO_Client.fileTransfer(file, sc);
       
           System.out.println("Total time taken in MS--"+(System.currentTimeMillis() - start));
    }
        
    public static void fileTransfer(File in, SocketChannel sc) throws IOException 
    {
    
    ByteBuffer buf = ByteBuffer.allocateDirect(32 * 1024);   
    
    FileChannel inChannel = new FileInputStream(in).getChannel();
      
    try 
    {
        long len;
        
        while((len = inChannel.read(buf)) != -1)
        {
            buf.flip();
            sc.write(buf);
            buf.clear();
        }
     } 
    finally 
    {
        if (inChannel != null) 
        {
            inChannel.close();
        }        
    }
  }
        
}
